package KMP;

import java.util.Arrays;

public class KMPDemo {
    public static void main(String[] args) {
        String str1 = "BBC ABCDAB ABCDABCDABDE";
        String str2 = "ABCDABD";
        int[] next = KMPNext(str2);
        System.out.println("next = " + Arrays.toString(next));
        int index = KMPSearch(str1,str2,next);
        System.out.println("index = " + index);
    }

    /**
     * KMP算法查找相同字符串第一个字符所在位置
     * @param str1:源字符串
     * @param str2:目标字符串
     * @param next:部分匹配表
     * @return:相同字符串第一个字符所在位置
     */
    public static int KMPSearch(String str1, String str2, int[] next){
        for(int i = 0, j = 0; i < str1.length(); i++){
            while(j > 0 && str1.charAt(i) != str2.charAt(j)){
                j = next[j - 1];
            }
            if(str1.charAt(i) == str2.charAt(j)){
                j++;
            }

            if(j == str2.length()){
                return i - j + 1;
            }
        }
        return -1;
    }

    /**
     * KMP部分匹配表
     * @param dest:目标字符串
     * @return:部分匹配表
     */
    public static int[] KMPNext(String dest){
        int[] next = new int[dest.length()];
        next[0] = 0;
        for(int i = 1, j = 0; i < dest.length(); i++){
            while(j > 0 && dest.charAt(i) != dest.charAt(j)){
                j = next[j - 1];
            }

            if(dest.charAt(i) == dest.charAt(j)){
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}
